package com.superpet.weixin.api.pet;

import com.jfinal.aop.Before;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.superpet.common.controller.BaseController;
import com.superpet.common.kits.ConstantKit;
import com.superpet.common.kits.DateKit;
import com.superpet.common.kits.NumberKit;
import com.superpet.common.model.*;
import com.superpet.weixin.api.wxrun.WxRunService;
import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

public class PetController extends BaseController {

    static PetService srv = PetService.me;

    public void savePet(){
        Long petId = getParaToLong("id",0L);
        Pets pet = Pets.dao.findById(petId);
        if(pet==null){
            pet = new Pets();
            pet.setPetNo(NumberKit.buildRandom(6)+"");
            pet.setUserid(getLoginUserId());
            pet.setUserNickName(getLoginUser().getNickName());
        }
        String avatar = getPara("avatar");
        String imgPrefix = srv.getImgPathPrefix();
        if(avatar.contains(imgPrefix)){//maybe contains some prefix if from edit
            avatar = avatar.substring(avatar.indexOf(imgPrefix)+imgPrefix.length());
        }
        pet.setAvatar(avatar);
        pet.setSex(getParaToInt("sex"));
        pet.setBirthday(getPara("birthday"));
        pet.setConstellation(DateKit.date2Constellation(getPara("birthday")));
        pet.setFeature(getPara("feature"));
        pet.setPetName(getPara("petName"));
        pet.setWeight(Double.parseDouble(getPara("weight")));
        pet.setIsNeuter(getParaToInt("isNeuter"));
        pet.setBreed(getPara("breed"));
        pet.setUpdateTime(DateKit.toTimeStr(new Date()));
        boolean result;
        if(pet.getId()==null){
            result = pet.save();
            Users user = Users.dao.findById(getLoginUserId());
            user.setPetsCount(user.getPetsCount()+1);
            user.update();
        }else{
            result = pet.update();
        }
        if(result){
            renderJson(Ret.ok("code", ConstantKit.CODE_SUCCESS).set("msg",ConstantKit.MSG_SUCCESS).set("petNo",pet.getPetNo()));
        }else{
            renderJson(Ret.fail("code", ConstantKit.CODE_FAIL).set("msg",ConstantKit.MSG_FAIL));
        }
    }

    public void getUserPetList(){
        List<Pets> pets = srv.getUserPetList(getLoginUserId());
        renderJson(Ret.ok("code",ConstantKit.CODE_SUCCESS).set("msg",ConstantKit.MSG_SUCCESS).set("pets",pets));
    }

    public void getSomeonePetList(){
        Long userId = getParaToLong("userId",0L);
        List<Pets> pets = srv.getUserPetList(userId);
        String userNickName = "";
        if(pets!=null && !pets.isEmpty()){
            userNickName = pets.get(0).getUserNickName();
        }
        renderJson(Ret.ok("code",ConstantKit.CODE_SUCCESS).set("msg",ConstantKit.MSG_SUCCESS).set("pets",pets)
                    .set("userNickName", userNickName));
    }

    public void getUserPetDet(){
        Long petId = getParaToLong("petId",0L);
        Pets pet = srv.getPetById(petId);
        List<PetPic> pics = srv.getUserPetPicList(petId,3);
        List<PetFeedLog> feeds = srv.getUserPetFeedByDayList(petId, DateKit.toDateStr(new Date()));
        PetFeedTotal petFeedTotal = srv.getPetFeedTotal(getLoginUserId(),petId);
        int isCollect = 0;
        int picLiker = 0;
        if(petFeedTotal!=null){
            isCollect = petFeedTotal.getIsCollect();
            picLiker = petFeedTotal.getPicLiker();
        }
        renderJson(Ret.ok("code",ConstantKit.CODE_SUCCESS).set("msg",ConstantKit.MSG_SUCCESS)
                .set("pet",pet).set("pics",pics).set("feeds",feeds).set("isCollect",isCollect)
                .set("picLiker",picLiker));
    }

    public void getUserPetFeedByDayList(){
        Long petId = getParaToLong("petId",0L);
        List<PetFeedLog> feeds = srv.getUserPetFeedByDayList(petId, DateKit.toDateStr(new Date()));
        renderJson(Ret.ok("code",ConstantKit.CODE_SUCCESS).set("msg",ConstantKit.MSG_SUCCESS).set("feeds",feeds));
    }

    @Before(Tx.class)
    public void feedPet() throws ParseException {
        Long petId = getParaToLong("petId",0L);
        Long userId = getParaToLong("userId",0L);
        if(petId>0 && userId>0){
            if(srv.getTodayFeedPet(petId,getLoginUserId(),DateKit.toDateStr(new Date()))==null){//today first time to feed
                String yesterday = DateKit.strToDateOffset(new Date(),-1);
                Integer feedVal = 0;
                if(userId==getLoginUserId()) {//feed myself
                    feedVal = WxRunService.me.getWxRunForFeedMyself(getWxSession().getOpenid(),yesterday);
                }else{
                    feedVal = WxRunService.me.getWxRunForFeed(getWxSession().getOpenid(),yesterday);
                }
                if(feedVal>0) {
                    //feed log
                    PetFeedLog pf = new PetFeedLog();
                    pf.setUserid(getLoginUserId());
                    pf.setPetid(petId);
                    pf.setPetUserid(userId);
                    pf.setFeedVal(feedVal);
                    pf.setUpdateTime(DateKit.toTimeStr(new Date()));
                    pf.setFeedDate(DateKit.toDateStr(new Date()));
                    pf.save();
                    //feed pet total
                    PetFeedTotal pfd = srv.getPetFeedTotal(getLoginUserId(), petId);
                    if (pfd != null) {
                        pfd.setFeedVal(pfd.getFeedVal() + feedVal);
                        pfd.setUpdateTime(DateKit.toTimeStr(new Date()));
                        pfd.update();
                    } else {
                        pfd = new PetFeedTotal();
                        pfd.setUserid(getLoginUserId());
                        pfd.setPetid(petId);
                        pfd.setPetUserid(userId);
                        pfd.setFeedVal(feedVal.longValue());
                        pfd.setUpdateTime(DateKit.toTimeStr(new Date()));
                        pfd.save();
                    }
                    //pet feed total
                    Pets pet = Pets.dao.findById(petId);
                    pet.setTotalEnergy(pet.getTotalEnergy() + feedVal);
                    //is level up?
                    if(pet.getTotalEnergy()>=Math.pow(2,pet.getLevelNo())*10000 ){
                        double nextLevelNeed = Math.pow(2,(pet.getLevelNo()+1))*10000;
                        pet.setNextLevelNeed(new Double(nextLevelNeed).longValue());
                        pet.setLevelNo(pet.getLevelNo()+1);
                    }
                    pet.update();

                    renderJson(Ret.ok("code", ConstantKit.CODE_SUCCESS).set("msg", ConstantKit.MSG_SUCCESS).set("feedVal", feedVal));
                }else if(feedVal==0 || feedVal==-1){//finish feed or has no weRun data
                    renderJson(Ret.ok("code", ConstantKit.CODE_SUCCESS).set("msg", ConstantKit.MSG_SUCCESS).set("feedVal", feedVal));
                }else{//error
                    renderJson(Ret.fail("code",ConstantKit.CODE_FAIL).set("msg",ConstantKit.MSG_FAIL).set("feedVal",feedVal));
                }
            }else{
                renderJson(Ret.ok("code",ConstantKit.CODE_SUCCESS).set("msg",ConstantKit.MSG_SUCCESS).set("hasFeed","1"));
            }
        }else{
            renderJson(Ret.fail("code",ConstantKit.CODE_FAIL).set("msg",ConstantKit.MSG_FAIL));
        }
    }

    public void getUserPetPicList(){
        Long petId = getParaToLong("petId",0L);
        List<PetPic> pics = srv.getUserPetPicList(petId,10);
        renderJson(Ret.ok("code",ConstantKit.CODE_SUCCESS).set("msg",ConstantKit.MSG_SUCCESS).set("pics",pics));
    }

    @Before(Tx.class)
    public void CollectPet(){
        Long petId = getParaToLong("petId",0L);
        Long userId = getParaToLong("userId",0L);
        Integer isCollect = getParaToInt("isCollect",0);
        PetFeedTotal pfd = srv.getPetFeedTotal(getLoginUserId(),petId);
        if(petId>0 && userId>0){
            if(pfd!=null){
                pfd.setIsCollect(isCollect);
                pfd.setUpdateTime(DateKit.toTimeStr(new Date()));
                pfd.update();
            }else{
                pfd = new PetFeedTotal();
                pfd.setUserid(getLoginUserId());
                pfd.setPetid(petId);
                pfd.setPetUserid(userId);
                pfd.setIsCollect(isCollect);
                pfd.setUpdateTime(DateKit.toTimeStr(new Date()));
                pfd.save();
            }
            PetHouse ph = srv.getPetHouse(getLoginUserId(),petId);
            if(ph!=null){
                ph.setActiveFlag(isCollect);
                ph.setUpdateTime(DateKit.toTimeStr(new Date()));
                ph.update();
            }else{
                ph = new PetHouse();
                ph.setUserid(getLoginUserId());
                ph.setPetid(petId);
                ph.setPetUserid(userId);
                ph.setActiveFlag(isCollect);
                ph.setUpdateTime(DateKit.toTimeStr(new Date()));
                ph.save();
            }
            renderJson(Ret.ok("code",ConstantKit.CODE_SUCCESS).set("msg",ConstantKit.MSG_SUCCESS));
        }else{
            renderJson(Ret.fail("code",ConstantKit.CODE_FAIL).set("msg",ConstantKit.MSG_FAIL));
        }
    }

    @Before(Tx.class)
    public void likePetPic(){
        Long petId = getParaToLong("petId",0L);
        Long userId = getParaToLong("userId",0L);
        Integer picLiker = getParaToInt("picLiker",0);
        PetFeedTotal pfd = srv.getPetFeedTotal(getLoginUserId(),petId);
        if(petId>0 && userId>0){
            if(pfd!=null){
                pfd.setPicLiker(picLiker);
                pfd.setUpdateTime(DateKit.toTimeStr(new Date()));
                pfd.update();
            }else{
                pfd = new PetFeedTotal();
                pfd.setUserid(getLoginUserId());
                pfd.setPetid(petId);
                pfd.setPetUserid(userId);
                pfd.setPicLiker(picLiker);
                pfd.setUpdateTime(DateKit.toTimeStr(new Date()));
                pfd.save();
            }
            Pets pet = Pets.dao.findById(petId);
            if(picLiker==1){
                pet.setPicLikeCount(pet.getPicLikeCount()+1);
            }else{
                pet.setPicLikeCount(pet.getPicLikeCount()-1);
            }
            pet.update();
            renderJson(Ret.ok("code",ConstantKit.CODE_SUCCESS).set("msg",ConstantKit.MSG_SUCCESS));
        }else{
            renderJson(Ret.fail("code",ConstantKit.CODE_FAIL).set("msg",ConstantKit.MSG_FAIL));
        }
    }

    public void getPetHouseList(){
        List<PetHouse> houses = srv.getPetHouseList(getLoginUserId());
        PetHouse topFriend = new PetHouse();
        if(houses!=null && !houses.isEmpty()){
            topFriend = houses.get(0);
        }
        renderJson(Ret.ok("code",ConstantKit.CODE_SUCCESS).set("msg",ConstantKit.MSG_SUCCESS)
                .set("pet",topFriend).set("petFriends",houses));
    }

    public void getMyFeedPetList(){
        List<PetFeedLog> feeds = srv.getMyFeedPetList(getLoginUserId());
        renderJson(Ret.ok("code",ConstantKit.CODE_SUCCESS).set("msg",ConstantKit.MSG_SUCCESS).set("myFeeds",feeds));
    }

    public void getFeedMyPetList(){
        List<PetFeedLog> feeds = srv.getFeedMyPetList(getLoginUserId());
        renderJson(Ret.ok("code",ConstantKit.CODE_SUCCESS).set("msg",ConstantKit.MSG_SUCCESS).set("feedMys",feeds));
    }

    public void getFeedPetList(){
        List<PetFeedLog> myFeed = srv.getMyFeedPetList(getLoginUserId());
        List<PetFeedLog> feedMy= srv.getFeedMyPetList(getLoginUserId());
        renderJson(Ret.ok("code",ConstantKit.CODE_SUCCESS).set("msg",ConstantKit.MSG_SUCCESS)
                      .set("myFeed",myFeed).set("feedMy",feedMy));
    }

    public void deletePetPic(){
        String petPicIds = getPara("petPicIds");
        srv.deletePetPic(petPicIds);
        renderJson(Ret.ok("code",ConstantKit.CODE_SUCCESS).set("msg",ConstantKit.MSG_SUCCESS));
    }

    public void getPetCardBg(){
        String cardBg = srv.getPetCardBg();
        String[] cardWords = srv.getCardRandomWords();
        Pets pet = srv.getUserRandomPet(getLoginUserId());
        if(StringUtils.isNotBlank(cardBg)){
            renderJson(Ret.ok("code",ConstantKit.CODE_SUCCESS).set("msg",ConstantKit.MSG_SUCCESS)
                          .set("cardBg",cardBg).set("masterWords",cardWords[0]).set("petWords",cardWords[1])
                          .set("petName",pet.getPetName()).set("blessingWords",cardWords[2])
                          .set("petAvatar",pet.getAvatar()));
        }else{
            renderJson(Ret.fail("code",ConstantKit.CODE_FAIL).set("msg",ConstantKit.MSG_FAIL));
        }
    }

}
